package com.mis.pos.service.impl;

import com.mis.pos.dto.AddItemDTO;
import com.mis.pos.entity.ItemEntity;
import com.mis.pos.form.ItemSearchForm;
import com.mis.pos.repository.ItemRepository;
import com.mis.pos.service.ItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author yuxiang
 * @CreatedDate 2019/10/30 17:43
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemRepository itemRepository;

    @Override
    public ItemEntity findOneById(Long itemId) {
        return itemRepository.findItemEntityById(itemId);
    }

    @Override
    public Map findAll(Integer pageSize, Integer pageNumber) {

        Map map = new HashMap();
        List<ItemEntity> itemEntityList = itemRepository.findAllLimit(pageSize,pageNumber);
        map.put("list",itemEntityList);
        map.put("count",itemRepository.countAll());
        return map;
    }

    @Override
    public int deleteByEntity(ItemEntity entity) {
        try {
            itemRepository.deleteById(entity.getId());
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    @Override
    public int updateEntity(ItemEntity entity) {
        try {
            itemRepository.updateEntity(entity.getId(),entity.getPrice());
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    @Override
    public List<ItemEntity> searchItemsByName(String itemName) {
        return itemRepository.findAllByItemName(itemName);
    }

    @Override
    public int save(ItemEntity itemEntity) {
        try {
            itemRepository.save(itemEntity);
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    @Override
    public int updateIsSaledById(Long itemId,int isSaled) {
        try {
            itemRepository.updateIsSaledById(itemId,isSaled);
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    @Override
    public List<String> getAllBrands() {
        return itemRepository.selectBrands();
    }

}
